package com.qf.controller2;

import com.qf.captcha.CaptchaCodeManager;
import com.qf.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;

/**
 * @author Wy
 * @version V1.0
 * @Project MavenDemo
 * @Package com.qf.controller2
 * @Description:
 * @Date 2022/7/9 16:21
 */
@RestController
@CrossOrigin("*")
@RequestMapping("/auth")
public class AuthController  {

      private  static  final Logger LOGGER= LoggerFactory.getLogger(AuthController.class);

      @GetMapping("/captchaImage")
       public  Object getCode() throws  Exception{
           //1.生成随机字符串
           String code = VerifyCodeUtils.generateVerifyCode(4);
           //2.验证码唯一id
           String uuid = UUID.randomUUID().toString(true);
           //3.验证码储存到内存中
           boolean b = CaptchaCodeManager.addToCache(uuid, code, 10);
           //4.判断验证码是否保存成功
            if(!b){
                  LOGGER.error("请求验证码出错", AdminResponseCode.AUTH_CAPTCHA_ERROR);
                  return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_FREQUENCY);
            }
           //生成图片
           ByteArrayOutputStream stream = new ByteArrayOutputStream();

           VerifyCodeUtils.outputImage(111, 36, stream,code);

           //6.将图片和唯一id返回
          try {
              HashMap<String,Object> data = new HashMap<>();
              data.put("uuid", uuid);
              data.put("img", Base64.encode(stream.toByteArray()));
              return  ResponseUtil.ok(data);
          }catch (Exception e){
              e.printStackTrace();
          }finally {
              stream.close();
          }

        return  null;

    }

     @GetMapping("/login")
      public Object login(@RequestBody String body){
         String code = JacksonUtil.parseString(body, "code");
         String password = JacksonUtil.parseString(body, "password");
         String username = JacksonUtil.parseString(body, "username");
         String uuid = JacksonUtil.parseString(body, "uuid");
          if(StringUtils.isEmpty(code)||StringUtils.isEmpty(password)||
                  StringUtils.isEmpty(username)||StringUtils.isEmpty(uuid)){

              return  ResponseUtil.badArgument();
          }

          //判断验证码是否错误
            //从缓存中获取验证码
         String cachedCaptcha = CaptchaCodeManager.getCachedCaptcha(uuid);

          if(!code.equalsIgnoreCase(cachedCaptcha)){

              return  AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_ERROR);
          }


         return  null;
      }

}
